package com.cnplan.auth.utils;

import com.cnplan.entity.SystemUser;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

/**
 * Created by Administrator on 2018/4/25.
 */
public class PasswordUtils {
    public static void encryptPassword(SystemUser user) {
        RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
        String algorithmName = "md5";
        int hashIterations = 2;
        user.setPasswordSalt(randomNumberGenerator.nextBytes().toHex());

        String hashPassword = new SimpleHash(
                algorithmName,
                user.getUserPassword(),
                ByteSource.Util.bytes(user.getPasswordSalt()),
                hashIterations).toHex();

        user.setUserPassword(hashPassword);
    }

    public static Boolean checkPassword(SystemUser user, String password) {

        String algorithmName = "md5";
        int hashIterations = 2;


        String hashPassword = new SimpleHash(
                algorithmName,
                password,
                ByteSource.Util.bytes(user.getPasswordSalt()),
                hashIterations).toHex();
        return hashPassword.equals(user.getUserPassword());

    }

    public static String getEncryptPassword(String salt, String password){
        String algorithmName = "md5";
        int hashIterations = 2;
        String hashPassword = new SimpleHash(algorithmName, password, ByteSource.Util.bytes(salt), hashIterations).toHex();
        return hashPassword;
    }
}
